'use strict';

const { readFileSync } = require('fs-extra');
const downit = require('./resumeableDownload');
const { getTrackDownloadUrl, ensureDir } = require('../components/utils');
const { decryptDownload } = require('decrypt-tracks');
const multibar = require('../components/multibar');

/**
 * Download the track, decrypt it and write it to a file.
 *
 * @param {Object} trackInfos
 * @param {Number} trackQualityId
 * @param {String} saveFilePath
 */
const downloadTrack = async (trackInfos, trackQualityId, saveFilePath, bar) => {
  // add bars
  if (global.bar) {
    bar = multibar.create(100, 0, { title: trackInfos.SNG_TITLE, speed: '0 Bytes' });
  }

  try {
    const trackDownloadUrl = getTrackDownloadUrl(trackInfos, trackQualityId);
    const dirpath = ensureDir(saveFilePath);
    const download = await downit(trackDownloadUrl, dirpath + trackInfos.SNG_ID + trackQualityId, {
      onprogress: (downloaded, total) => {
        // control bars
        if (global.bar) {
          bar.update((100 * downloaded) / total, { title: trackInfos.SNG_TITLE });
        }
      },
    });
    return decryptDownload(readFileSync(download), trackInfos.SNG_ID);
  } catch (err) {
    throw err;
  }
};

module.exports = downloadTrack;
